package com.etc.demo.controller;

import com.etc.demo.utils.JDBC;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//驱动器
@RestController
public class LoginController {

//    登录驱动
    @GetMapping("login")
    public String login(String username,String password) throws SQLException {
        if (username == null || username.length() <= 0){
            return "请输入用户名";
        }
        if (password == null || password.length() <= 0){
            return "请输入密码";
        }
        Connection con = JDBC.getCon();
        PreparedStatement p = con.prepareStatement("select * from user where username = ?");
        p.setString(1,username);
        ResultSet resultSet = p.executeQuery();
        String password1 = "";
        while (resultSet.next()){
            password1 = resultSet.getString("password");
        }
        if (password1.equals(password)){
            return "1";
        }else {
            return "0";
        }
    }


//    注册驱动
    @GetMapping("add")
    public String userAdd(String username,String password,String loginname) throws SQLException {
        if (username == null || username.length() <= 0){
            return "请输入用户名";
        }
        if (password == null || password.length() <= 0){
            return "请输入密码";
        }
        if (loginname == null || loginname.length() <= 0){
            return "请输入名字";
        }

        //获取链接对象
        Connection con = JDBC.getCon();
        //获取执行器
        PreparedStatement p = con.prepareStatement("insert into user (username,password,loginname) value (?,?,?)");
        p.setString(1,username);
        p.setString(2,password);
        p.setString(3,loginname);

        int result = p.executeUpdate();
        if (result == 1){
            return "1";
        }else{
            return "0";
        }
    }
}
